<?php


namespace App\Bizs\Mp1;


use App\Exceptions\BizException;
use App\Models\GiveModel;
use App\Models\UserModel;
use App\Models\WannaModel;
use App\Supports\DateSupport;
use Base\BaseBiz;
use Base\BaseModel;
use Lib\Log;

class GiveBiz extends BaseBiz
{
    public function sendGive($params, $uid)
    {
        $insertData = [];
        if (empty($params['name'])) {
            throw new BizException('请输入名字');
        }
        $insertData['name'] = $params['name'];
        if (empty($params['age_month'])) {
            $params['age_month'] = -1;
        }
        $insertData['age_month'] = $params['age_month'];
        if (!empty($params['gender'])) {
            $insertData['gender'] = $params['gender'];
        }
        if (isset($params['nojj'])) {
            $insertData['nojj'] = $params['nojj'] ? 1 : 0;
        }
        if (isset($params['worm'])) {
            $insertData['worm'] = $params['worm'] ? 1 : 0;
        }
        if (isset($params['inject'])) {
            $insertData['inject'] = $params['inject'];
        }
        if (!empty($params['source'])) {
            $insertData['source'] = $params['source'];
        }
        if (!empty($params['remark'])) {
            $insertData['remark'] = $params['remark'];
        }
        if (!empty($params['images'])) {
            $insertData['images'] = $params['images'];
        }
        if (!empty($params['column'])) {
            $insertData['column'] = $params['column'];
        }
        if (!empty($params['friend_name'])) {
            $insertData['friend_name'] = $params['friend_name'];
        }
        if (!empty($params['friend_mobile'])) {
            $insertData['friend_mobile'] = $params['friend_mobile'];
        }
        if (!empty($params['friend_weixin'])) {
            $insertData['friend_weixin'] = $params['friend_weixin'];
        }

        $insertData = array_merge($insertData, [
            'uid' => $uid,
            'create_time' => DateSupport::nowDate()
        ]);
        try {
            $insert = (new GiveModel())->insertGive($insertData);
            return [
                'insert' => $insert
            ];
        } catch (\Exception $e) {
            throw new BizException("发送送养信息时出现问题." . $e->getMessage());
        }
    }

    public function editGive($params, $uid, $user)
    {
        if (empty($params['give_id'])) {
            throw new BizException('缺少送养id');
        }
        $saveData = [];
        $oriData = (new GiveModel())->getGiveRow($params['give_id']);
        if ($oriData['uid'] != $uid || $user['is_admin'] != 1) {
            throw new BizException('只有当前用户或管理员可以编辑');
        }
        if (!empty($params['name']) && $params['name'] != $oriData['name']) {
            $saveData['name'] = $params['name'];
        }
        if (!empty($params['age_month']) && $params['age_month'] != $oriData['age_month']) {
            $saveData['age_month'] = $params['age_month'];
        }
        if (!empty($params['gender'])) {
            $insertData['gender'] = $params['gender'];
        }
        if (!empty($params['nojj']) && $params['nojj'] != $oriData['nojj']) {
            $saveData['nojj'] = $params['nojj'];
        }
        if (!empty($params['worm']) && $params['worm'] != $oriData['worm']) {
            $saveData['worm'] = $params['worm'];
        }
        if (!empty($params['inject']) && $params['inject'] != $oriData['inject']) {
            $saveData['inject'] = $params['inject'];
        }
        if (!empty($params['source']) && $params['source'] != $oriData['source']) {
            $saveData['source'] = $params['source'];
        }
        if (!empty($params['remark']) && $params['remark'] != $oriData['remark']) {
            $saveData['remark'] = $params['remark'];
        }
        if (!empty($params['images']) && $params['images'] != $oriData['images']) {
            $saveData['images'] = $params['images'];
        }
        if (!empty($params['friend_name']) && $params['friend_name'] != $oriData['friend_name']) {
            $saveData['friend_name'] = $params['friend_name'];
        }
        if (!empty($params['friend_mobile']) && $params['friend_mobile'] != $oriData['friend_mobile']) {
            $saveData['friend_mobile'] = $params['friend_mobile'];
        }
        if (!empty($params['friend_weixin']) && $params['friend_weixin'] != $oriData['friend_weixin']) {
            $saveData['friend_weixin'] = $params['friend_weixin'];
        }
        if (empty($saveData)) {
            throw new BizException('没有要修改的数据');
        }

        $saveData = array_merge($saveData, [
            'uid' => $uid,
            'modify_time' => DateSupport::nowDate()
        ]);
        try {
            $update = (new GiveModel())->updateGive(['id' => $params['give_id']], $saveData);
            return [
                'update' => $update
            ];
        } catch (\Exception $e) {
            throw new BizException("修改送养信息时出现问题." . $e->getMessage());
        }
    }

    /**
     * 获取送养列表
     * @param $params
     * @param $uid
     * @return array
     */
    public function getGiveList($params, $uid, $user = [])
    {
        $whereArr = [
            'is_del' => 0
        ];
        if (!empty($params['column'])) {
            $whereArr['column'] = $params['column'];
        }
        if (!empty($params['user_id'])) {
            $whereArr['uid'] = $params['user_id'];
        }
        if (!empty($params['my_wanna']) && $params['my_wanna'] == 1) {
            $myWanna = (new WannaModel())->getWannaList([
                "uid" => $uid,
                "is_del" => 0
            ], ["give_id"]);
            if (empty($myWanna)) {
                return [
                    'count' => 0,
                    'data' => []
                ];
            }
            $whereArr["id"] = array_column($myWanna, 'give_id');
        }

        if ((!empty($params['need_verify']) && $params['need_verify'] == 1)) {
            $whereArr['verify'] = 0;
        }

        // 管理员可以看所有待审核的, 普通人只能看已审核的或者自己的
        if (!$user['is_admin']) {
            $whereArr['OR'] = [
                "verify" => 1,
                'uid' => $uid
            ];
        }
        $count = (new GiveModel())->getGiveListCount($whereArr);
        if ($count <= 0) {
            return [
                'count' => 0,
                'data' => []
            ];
        }
        $data = (new GiveModel())->getGiveListByPage($whereArr, 1, 200);
        // $data = (new GiveModel())->getGiveListByPage($whereArr, $params['page'] ?? 1, $params['limit'] ?? 0);

        $users = (new UserModel())->getUserDirByUid(array_column($data, 'uid'), ['id', 'nickname', 'icon']);
        foreach ($data as &$v) {
            $v['user_nickname'] = $users[$v['uid']]['id'];
            $v['user_icon'] = $users[$v['uid']]['icon'];
            if ($v['verify'] == 0) {
                $v['name'] = "[待审核] {$v['name']}";
            }
            if ($v['verify'] == 2) {
                $v['name'] = "[审核拒绝] {$v['name']}";
            }
        }

        return [
            'count' => $count,
            'data' => $data
        ];
    }

    public function deleteGive($params, $uid)
    {
        if (empty($params['id'])) {
            throw new BizException('请指定要删除的送养id');
        }
        $give = (new GiveModel())->getGiveRowById($params['id'], ['id', 'uid']);
        if (empty($give)) {
            throw new BizException('这条数据不存在');
        }
        if ($give['uid'] != $uid) {
            throw new BizException('你不能删除这条送养信息');
        }
        try {
            $delete = (new GiveModel())->fakeDeleteGive($params['id']);
            return [
                'delete' => $delete
            ];
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            throw new BizException('删除失败');
        }
    }

    /**
     * 获取送养详情
     * @param $params
     * @param $uid
     * @return array
     * @throws BizException
     */
    public function getGiveDetail($params, $uid)
    {
        if (empty($params['id'])) {
            throw new BizException('缺少id');
        }
        $give = (new GiveModel())->getGiveRow($params['id']);

        if (empty($give)) {
            throw new BizException('该送养信息不存在');
        }
        $currUser = $uid > 0 ? (new UserModel())->getUserByUid($uid) : [];
        if (!$currUser['is_admin'] && in_array($give['verify'], [0, 2]) && $uid != $give['uid']) {
            throw new BizException('该信息未审核');
        }
        if (in_array($give['verify'], [0, 2])) {
            $give['name'] = [
                0 => '[待审核]',
                2 => '[审核拒绝]'
            ][$give['verify']] . "{$give['name']}";
        }

        $user = (new UserModel())->getUserDirByUid([$give['uid']]);

        $wanna = (new WannaModel())->getWannaRow([
            'give_id' => $params['id'],
            'uid' => $uid
        ]);

        $give['create_user_info'] = $user[$give['uid']] ?: [];
        $give['iwanna'] = !empty($wanna);

        // 如果访问自己的，可以看到想要的列表
        if ($give['uid'] == $uid) {
            $wannaList = (new WannaModel())->getWannaList([
                'give_id' => $params['id']
            ]);
            $users = (new UserModel())->getUserDirByUid(array_column($wannaList, 'uid'));
            foreach ($wannaList as &$v) {
                $v['user'] = $users[$v['uid']];
            }
        } else {
            $wannaList = [];
        }
        $give['wanna_list'] = $wannaList;

        // 增加访问量
        (new GiveModel())->setGiveInc(['id' => $params['id']], 'view_count');

        return $give;
    }

    /**
     * 想要
     * @param $params
     * @param $uid
     * @return array
     * @throws BizException
     */
    public function wanna($params, $uid)
    {
        if (empty($params['give_id'])) {
            throw new BizException('请指定要领养的id');
        }
        if (empty($params['content'])) {
            throw new BizException('说点什么吧？');
        }

        $give = (new GiveModel())->getGiveRow($params['give_id']);
        if (empty($give)) {
            throw new BizException('这个送养信息不存在');
        }
        if ($give['uid'] == $uid) {
            throw new BizException('不能领养自己发送的宠物');
        }
        $wanna = (new WannaModel())->getWannaRow([
            'give_id' => $params['give_id'],
            'uid' => $uid,
            'is_del' => 0
        ]);
        if (!empty($wanna)) {
            throw new BizException('你已经想要啦，我们会帮你催促主人的');
        }

        try {
            $insert = (new WannaModel())->insertWanna([
                'give_id' => $params['give_id'],
                'uid' => $uid,
                'content' => $params['content'],
                'create_time' => DateSupport::nowDate(),
                'is_del' => 0
            ]);

            // 计算想要数量
            $update = (new GiveModel())->updateGive([
                'id' => $params['give_id']
            ], [
                'wanna_count' => (new WannaModel())->getWannaCount([
                    'give_id' => $params['give_id']
                ])
            ]);

            // 给主人发消息
            $insertMsg = (new MessageBiz())->sendMessage(
                $give['uid'],
                'wanna',
                $give['id'],
                $uid,
                "【新的领养请求】" . $params['content']
            );

            return [
                'insert' => $insert,
                'update' => $update,
                'insertMsg' => $insertMsg
            ];
        } catch (\Exception $e) {
            throw new BizException('保存数据失败');
        }
    }

    public function verify($params, $uid)
    {
        if (empty($params['give_id'])) {
            throw new BizException('请指定审核的送养id');
        }
        $give = (new GiveModel())->getGiveRow($params['give_id']);
        if (empty($give)) {
            throw new BizException('这条送养信息不存在');
        }
        if (empty($params['verify'])) {
            throw new BizException('请指定审核是否通过');
        }
        if ($params['verify'] == -1 && empty($params['refuse_reason'])) {
            throw new BizException('请填写拒绝理由');
        }
        $update = (new GiveModel())->updateGive([
            'id' => $params['give_id']
        ], [
            'verify' => $params['verify'],
            'refuse_reason' => $params['refuse_reason'] ?: "",
            'modify_time' => DateSupport::nowDate(),
            'modify_user' => $uid
        ]);
        $msg = "你发送的送养信息：{$give['name']}" . (($params['verify'] == 1) ? " 审核通过了" : " 没有审核通过，拒绝理由是{$params['refuse_reason']}。");
        $sendMsg = (new MessageBiz())->sendMessage($give['uid'], 'give', $params['give_id'], 10001, $msg);

        return [
            'update' => $update,
            'sendMsg' => $sendMsg
        ];
    }

    /**
     * 获取想要人的列表
     */
    public function getWannaList($params, $uid)
    {
        if (empty($params['give_id'])) {
            throw new BizException('需要指定送养id');
        }
        $give = (new GiveModel())->getGiveRow($params['give_id']);
        if (empty($give)) {
            throw new BizException('该送养信息不存在');
        }
        if ($give['uid'] != $uid) {
            throw new BizException('你不是主人，不能看哦');
        }
        $wanna = (new WannaModel())->getWannaList([
            "give_id" => $params['give_id'],
            'is_del' => 0
        ]);
        if (empty($wanna)) return [];

        $users = (new UserModel())->getUserDirByUid(array_column($wanna, 'uid'));
        $gives = (new GiveModel())->getGiveDir(array_column($wanna, 'give_id'));
        foreach ($wanna as &$v) {
            $v['user'] = $users[$v['uid']] ?? [];
            $v['give'] = $gives[$v['give_id']] ?? [];
        }
        return $wanna;
    }

    /**
     * 标记已经送出
     */
    public function given($params, $uid)
    {
        if (empty($params['give_id'])) {
            throw new BizException('需要指定送养id');
        }
        $give = (new GiveModel())->getGiveRow($params['give_id']);
        if (empty($give)) {
            throw new BizException('该送养信息不存在');
        }
        // give数据标记送给谁了，不知道送给谁就标记-1
        // wanna也标记送给谁了，没得到的都got记2
        $updateGiveData = [
            "modify_time" => DateSupport::nowDate(),
            "modify_user" => $uid
        ];
        if (empty($params['give_user_id'])) {
            $updateGiveData['give_user'] = -1;
        } else {
            $updateGiveData['give_user'] = $params['give_user_id'];
        }
        try {
            $updateGive = false;
            $updateWanna = false;
            $updateWanna2 = false;
            (new BaseModel())->baseTransaction(function($db) use($params, $updateGiveData, $uid, &$updateGive, &$updateWanna, &$updateWanna2) {
                $updateGive = (new GiveModel())->updateGive([
                    "id" => $params['give_id']
                ], $updateGiveData);
                // 先标记谁都没得到，然后如果有人得到了，给这个人标记得到了
                $updateWanna = (new WannaModel())->updateWanna([
                    "give_id" => $params['give_id']
                ], [
                    "got" => 2,
                    "modify_time" => DateSupport::nowDate(),
                    "modify_user" => $uid
                ]);
                $updateWanna2 = false;
                if (!empty($params['give_user_id']) && $params['give_user_id'] > 0) {
                    $updateWannaData = [
                        "got" => 1,
                        "modify_time" => DateSupport::nowDate(),
                        "modify_user" => $uid
                    ];
                    if (!empty($params['give_remark'])) {
                        $updateWannaData['got_remark'] = $params['give_remark'];
                    }
                    $updateWanna2 = (new WannaModel())->updateWanna([
                        "give_id" => $params['give_id'],
                        "uid" => $params['give_user_id']
                    ], $updateWannaData);
                }
            }, []);

            return [
                'updateGive' => $updateGive,
                'updateWanna' => $updateWanna,
                'updateWanna2' => $updateWanna2
            ];
        } catch (\Exception $e) {
            Log::error('确认送养时出现问题:' . $e->getMessage());
            throw new BizException("确认送养时出现问题");
        }
    }
}
